/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.handlers.meta;

import cn.ac.iie.di.ban.news.server.util.HostInfoKeeper;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author zwlin
 */
public class MetaCollectHandler implements HandlerI {

	private static HostInfoKeeper keeper = null;

	public static void init(HostInfoKeeper keeper) {
		MetaCollectHandler.keeper = keeper;
	}

	@Override
	public void init() throws Exception {
		if (keeper == null) {
			throw new Exception("HostInfoKeep not set .");
		}
	}

	@Override
	public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
		//get host and check exist
		String host = request.getParameter("host");
		if (host == null || host.trim().isEmpty()) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "param host not exist.");
			return;
		}
		host = host.trim();

		//get type and check exist
		String type = request.getParameter("type");
		if (type == null || type.trim().isEmpty()) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "param type not exist.");
			return;
		}
		type = type.trim().toLowerCase();

		//reg host with type
		switch (type) {
			case "test":
				keeper.regTestHost(host);
				break;
			case "online":
				keeper.regOnlineHost(host);
				break;
			default:
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot recognize type");
				return;
		}
		response.setStatus(HttpServletResponse.SC_OK);
	}

}
